package rpc.init;

import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import rpc.annotation.ServiceName;

import java.util.HashMap;
import java.util.Map;

/**
 * 读取当前项目中暴露出去的服务
 */
//@Component
public class ServiceInit implements ApplicationContextAware, ApplicationRunner {

    public static Map<String,Object> serverBeanMap=new HashMap<>();

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) {
        //beanName+bean实例
        Map<String, Object> beansWithAnnotation = this.applicationContext.getBeansWithAnnotation(ServiceName.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            ServiceName annotation = entry.getValue().getClass().getAnnotation(ServiceName.class);
            String classify = annotation.classify();
            if(serverBeanMap.containsKey(classify)){
                throw new RuntimeException("classify重名");
            }
            serverBeanMap.put(classify,entry.getValue());
        }
    }

}
